package com.nlscan.ncomgateway.core.sdk.udp

import android.content.Context
import com.nlscan.ble.util.NLogUtil
import com.nlscan.ble.util.Utils
import com.nlscan.ncomgateway.core.common.AppConfig
import com.nlscan.ncomgateway.core.data.preference.SettingsPreferenceManager
import net.x52im.mobileimsdk.android.ClientCoreSDK
import net.x52im.mobileimsdk.android.conf.ConfigEntity
import net.x52im.mobileimsdk.android.core.LocalDataReciever
import net.x52im.mobileimsdk.android.core.LocalDataSender
import net.x52im.mobileimsdk.android.core.LocalSocketProvider
import java.net.DatagramSocket

/**
 * <pre>
 *  author: lin.qing
 *  time  : 2023/6/15
 *  desc  :
 * </pre>
 */
object UdpManager {

    fun init(context: Context) {

        // 确保MobileIMSDK被初始化哦（整个APP生生命周期中只需调用一次哦）
        // 提示：在不退出APP的情况下退出登陆后再重新登陆时，请确保调用本方法一次，不然会报code=203错误哦！
        IMClientManager.getInstance(context.applicationContext).initMobileIMSDK()
    }

    fun release() {
        // 释放IM占用资源
        IMClientManager.getInstance(Utils.getApp()).release()
    }

    fun setUdpConfig() {
        setUdpConfig(
            SettingsPreferenceManager.getIpOutputHostname(),
            SettingsPreferenceManager.getIpOutputPort().toInt()
        )
    }

    fun setUdpConfig(hostname: String, iPort: Int) {
        // 无条件重置socket，防止首次登陆时用了错误的ip或域名，下次登陆时sendData中仍然使用老的ip
        // 说明：本行代码建议仅用于Demo时，生产环境下是没有意义的，因为你的APP里不可能连IP都搞错了
        //LocalSocketProvider.getInstance().closeLocalSocket()
        ConfigEntity.serverIP = hostname
        ConfigEntity.serverPort = iPort
        // 固定 localPort
        ConfigEntity.localPort = AppConfig.DEFAULT_UDP_LOCAL_PORT
        //重置udp localSocket
        LocalSocketProvider.getInstance().resetLocalSocket()
    }


    fun sendBytesDataAsync(data: String) {
        // 发送消息（Android系统要求必须要在独立的线程中发送哦）
        object : LocalDataSender.SendBytesDataAsync(data.toByteArray()) {
            override fun onPostExecute(code: Int) {
                if (code == 0) NLogUtil.i("SendBytesDataAsync send udp data succeed") else
                    NLogUtil.e("SendBytesDataAsync send udp data failed! code: $code")
            }
        }.execute()

//        LocalSocketProvider.getInstance().

    }

    fun getLocalSocket(): DatagramSocket? {
        return LocalSocketProvider.getInstance().localSocket
    }

    fun getLocalPort(): Int {
        return getLocalSocket()?.localPort ?: -1
    }

    fun startListenLocalPort() {
        //将自动监听标志位设置为true (网络切换时自动恢复)
        ClientCoreSDK.autoListenPort = true

        //[fix] 开始监听前先初始化 Socket，修复 Socket close导致异常
        LocalSocketProvider.getInstance().localSocket
        LocalDataReciever.getInstance().startup()
    }

    fun stopListenLocalPort() {
        // todo 验证没有效果
        NLogUtil.i("stopListenLocalPort")
        //将自动监听标志位设置为true (网络切换时自动恢复)
        ClientCoreSDK.autoListenPort = false

        LocalDataReciever.getInstance().stop()
//        LocalSocketProvider.getInstance().closeLocalSocket()
    }


    fun updateUdpConfigAndStartListenPort(){
        setUdpConfig()
        startListenLocalPort()
    }


    fun getLocalDataReceiver(): LocalDataReciever? {
        return LocalDataReciever.getInstance()
    }


}